package com.epam.command.logic;

import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import org.jasypt.util.password.BasicPasswordEncryptor;

import com.epam.dao.DAOFactory;
import com.epam.dao.DAOFactory.DAOType;
import com.epam.dao.intf.IUserDAO;
import com.epam.entity.User;


public class LoginLogic {


	public static boolean authorize(String login, String plainPassword) {
		IUserDAO userDAO = (IUserDAO) DAOFactory.INSTANCE.getDAO(DAOType.USER);
		BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
		
		User user = userDAO.findByLogin(login);
		if (user == null || !passwordEncryptor.checkPassword(plainPassword, user.getPassword())) {

			return false;
		}
		
		return true;
	}

	public static boolean register(String login, String plainPassword) {
		IUserDAO userDAO = (IUserDAO) DAOFactory.INSTANCE.getDAO(DAOType.USER);
		boolean result;
		BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
		
		if (userDAO.findByLogin(login) == null) {
			String password = passwordEncryptor.encryptPassword(plainPassword);
			User user = new User(login, password);
			try {
				userDAO.insert(user);
			} catch (SQLException e) {
				e.printStackTrace();
			}

			result = true;
		} else {
			result = false;
		}
		return result;
	}

	public static void initializeSession(HttpSession session, String login) {
		IUserDAO userDAO = (IUserDAO) DAOFactory.INSTANCE.getDAO(DAOType.USER);

		session.setAttribute("login", login);
		session.setAttribute("user_id", userDAO.findByLogin(login).getId());
		session.setAttribute("role", userDAO.findByLogin(login).getRole());
	}
	
	public String encryptPassword(String plainPassword) {
		BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
		String encryptedPassword = passwordEncryptor.encryptPassword(plainPassword);
		
		return encryptedPassword;
	}
	
}